package com.mlamp.二叉树;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.stream.Collectors;

public class 二叉树路径和III {

    public static void main(String[] args) {
        TreeNode root = new TreeNode(10);
        root.left = new TreeNode(5);
        root.right = new TreeNode(-3);
        root.left.left = new TreeNode(3);
        root.left.right = new TreeNode(2);
        root.right.right = new TreeNode(11);
        root.left.left.left = new TreeNode(3);
        root.left.left.right = new TreeNode(-2);
        root.left.right.right = new TreeNode(1);
        二叉树路径和III instance = new 二叉树路径和III();
        instance.printTree(root);
        instance.pathSum(root, 8);
        if (!instance.res.isEmpty()){
            System.out.println(JSON.toJSONString(instance.res));
        }
    }

    private List<List<Integer>> res = new ArrayList<>();

    public void robot(TreeNode root, int sum, LinkedList<TreeNode> path) {
        path.add(root);
        sum -= root.value;
        if (sum == 0) {
            res.add(new ArrayList<>(path.stream().map(item -> item.value).collect(Collectors.toList())));
            return;
        }
        if (root.left != null) {
            robot(root.left, sum, path);
            path.removeLast();
        }
        if (root.right != null) {
            robot(root.right, sum, path);
            path.removeLast();
        }
    }

    public void pathSum(TreeNode root, int sum) {
        if (root == null) return;
        LinkedList<TreeNode> trace = new LinkedList<>();
        robot(root, sum, trace);
        pathSum(root.left, sum);
        pathSum(root.right, sum);
    }


    public void printTree(TreeNode root) {
        if (root == null) return;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                if (poll.left != null) queue.offer(poll.left);
                if (poll.right != null) queue.offer(poll.right);
                sb.append(poll.value).append(" ");
            }
            System.out.println(sb.toString());
        }
    }

    public static class TreeNode {
        int value;
        TreeNode left;
        TreeNode right;

        public TreeNode(int value) {
            this.value = value;
        }
    }
}


